package com.iemes.service.impl.workcenter_model;

import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.iemes.entity.OperationFormMap;
import com.iemes.entity.SfcStepFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.UDefinedDataValueFormMap;
import com.iemes.entity.WorkCenterFormMap;
import com.iemes.entity.WorkResourceFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.WorkcenterModel.WorkResourceMapper;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.workcenter_model.WorkResourceService;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class WorkResourceServiceImpl implements WorkResourceService {
	@Inject
	private WorkResourceMapper workResourceMapper;
	
	@Inject
	private BaseMapper baseMapper;
	
	private Logger log = Logger.getLogger(this.getClass());

	@Override
	@Transactional
	public void saveWorkResource(WorkResourceFormMap workResourceFormMap) throws BusinessException {
		try {
			String id = workResourceFormMap.getStr("id");
			String resourceNo = workResourceFormMap.getStr("resource_no");
			
			if(StringUtils.isEmpty(resourceNo)) {
				throw new BusinessException("资源编号不能为空，请输入！");
			}	
			
			String worklineId = workResourceFormMap.getStr("workline_id");
			if (!StringUtils.isEmpty(worklineId)) {
				List<WorkCenterFormMap> listWorkCenterFormMap = baseMapper.findByAttribute("id", worklineId, WorkCenterFormMap.class);
				if (!ListUtils.isNotNull(listWorkCenterFormMap)) {
					String errMessage = "未检索到相关的所属工作中心信息，请确认对应的工作中心信息是否存在或被删除";
					throw new BusinessException(errMessage);
				}
			}
			
			WorkResourceFormMap workResourceFormMap2 = new WorkResourceFormMap();
			workResourceFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			workResourceFormMap2.put("resource_no", resourceNo);
			List<WorkResourceFormMap> listWorkResourceFormMap = workResourceMapper.findByNames(workResourceFormMap2);
			
			//如果编号存在，就执行更新，不存在就执行新增
			if (ListUtils.isNotNull(listWorkResourceFormMap)) {
				//更新 
				WorkResourceFormMap workResourceFormMap3 = new WorkResourceFormMap();
				workResourceFormMap3 = listWorkResourceFormMap.get(0);
				id = workResourceFormMap3.getStr("id");
				workResourceFormMap.set("id", id);
				
				workResourceMapper.editEntity(workResourceFormMap);
			}else {
				//新增
				id = UUIDUtils.getUUID();
				workResourceFormMap.set("id", id);
				workResourceMapper.addEntity(workResourceFormMap);
			}

			//2.添加或更新自定义数据信息					
			UDefinedDataValueFormMap uDefinedDataValueFormMap = new UDefinedDataValueFormMap();
			uDefinedDataValueFormMap.put("data_type_detail_id",id);
			baseMapper.deleteByNames(uDefinedDataValueFormMap);
			//插入自定义数据字段表
			String dataValue = workResourceFormMap.getStr("udefined_data");
			if (!StringUtils.isEmpty(dataValue)) {
				JSONArray jsonArray = JSONArray.fromObject(dataValue);
				for (int i=0;i<jsonArray.size();i++) {
					JSONObject objectRow = jsonArray.getJSONObject(i);
					JSONObject objectFieldCell = objectRow.getJSONObject("key");
					JSONObject objectValueCell = objectRow.getJSONObject("value");
					
					String filedId = objectFieldCell.getString("value");
					String filedValue = objectValueCell.getString("value");

					UDefinedDataValueFormMap uDefinedDataValueFormMapNew = new UDefinedDataValueFormMap();
					uDefinedDataValueFormMapNew.put("id", UUIDUtils.getUUID());
					uDefinedDataValueFormMapNew.put("site_id", ShiroSecurityHelper.getSiteId());
					uDefinedDataValueFormMapNew.put("data_type_detail_id", id);
					uDefinedDataValueFormMapNew.put("udefined_data_filed_id", filedId);
					uDefinedDataValueFormMapNew.put("value", filedValue);
					uDefinedDataValueFormMapNew.put("create_user", ShiroSecurityHelper.getCurrentUsername());
					uDefinedDataValueFormMapNew.put("create_time", DateUtils.getStringDateTime());
					
					baseMapper.addEntity(uDefinedDataValueFormMapNew);
				}
			}
			
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("资源保存失败！" + e.getMessage());
		}
	}

	@Override
	@Transactional
	public void delWorkResource(String workResourceId) throws BusinessException {
		try {
			// 1.如果资源绑定了操作，则不允许删除
			OperationFormMap operationFormMap = new OperationFormMap();
			operationFormMap.put("default_resource", workResourceId);
			List<OperationFormMap> listOperationFormMap = baseMapper.findByNames(operationFormMap);
			if (ListUtils.isNotNull(listOperationFormMap)) {
				String bindOperationNo = "";
				for(int i=0;i<listOperationFormMap.size();i++) {
					OperationFormMap map = listOperationFormMap.get(i);
					if(StringUtils.isEmpty(bindOperationNo)) {
						bindOperationNo = map.getStr("operation_no");
					}else {
						bindOperationNo += "," + map.getStr("operation_no");
					}
				}
				throw new BusinessException("此资源绑定了操作 " + bindOperationNo + "，无法执行删除！");
			}
			
			// 2.判断资源是否已被使用，若被使用，则不允许删除，否则允许删除
			SfcStepFormMap sfcStepFormMap = new SfcStepFormMap();
			sfcStepFormMap.put("where", " where work_resource_id ='"+ workResourceId + "'");
			List<SfcStepFormMap> listSfcStepFormMap= baseMapper.findByWhere(sfcStepFormMap);
			if (ListUtils.isNotNull(listSfcStepFormMap)) {
				throw new BusinessException("此资源已用于生产，不可删除！");
			}

			// 3.删除资源表
			WorkResourceFormMap workResourceFormMap = new WorkResourceFormMap();
			workResourceFormMap.put("id", workResourceId);
			workResourceMapper.deleteByNames(workResourceFormMap);
			
			// 4.删除自定义数据表				
			UDefinedDataValueFormMap uDefinedDataValueFormMap = new UDefinedDataValueFormMap();
			uDefinedDataValueFormMap.put("data_type_detail_id",workResourceId);
			baseMapper.deleteByNames(uDefinedDataValueFormMap);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("资源删除失败！" + e.getMessage());
		}
	}

}
